// pages/connection/connection.js
const app = getApp()
const util = require('../../utils/util.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        connecting: false,
        loadingMsg: app.globalData.isZh ? '正在搜索蓝牙' : 'Searching for a device',
        failedType: 0,
        errTitle: "",
        errSubtitle: "",
        timer: null,
        isZh: app.globalData.isZh,
        baseURL: app.globalData.baseURL,
        routeName:""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(option) {
        if (!app.globalData.isZh) {
            wx.setNavigationBarTitle({ title: 'Connect the Device' })
        }
        this.data.routeName=option.name
        console.log(this.data.routeName);
    },
    onUnload() {
        clearTimeout(this.data.timer);
        this.setData({ failedType: 0, timer: null });
    },
    connect() {
        this.setData({ connecting: true, failedType: 0, loadingMsg: this.data.isZh ? '正在获取权限' : 'Getting Authorization' });
        // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.bluetooth" 这个 scope
        wx.getSetting({
            success: (res) => {
                // console.log("蓝牙权限", res.authSetting['scope.bluetooth'])
                // (1) 微信授权已关闭，弹窗打开
                if (res.authSetting['scope.bluetooth'] != undefined && res.authSetting['scope.bluetooth'] == false) {
                    wx.showToast({ title: this.data.isZh ? '请授权' : 'Please authorize', icon: "error", mask: true })
                    wx.openSetting({
                        success: (authData) => {
                            if (authData.authSetting['scope.bluetooth'] == true) {
                                // wx.showToast({ title: this.data.isZh ? '授权成功' : 'Authorized', icon: "success", mask: true })
                                this.openBluetooth(); // 打开蓝牙适配器 
                            } else {
                                wx.showToast({ title: this.data.isZh ? '授权失败' : 'Unauthorized', icon: "error", mask: true });
                                this.setData({ connecting: false, failedType: 1 });
                                this.showErr();
                            }
                        }
                    })
                }
                // (2) 'scope.bluetooth'属性不存在，需要授权
                if (res.authSetting['scope.bluetooth'] == undefined) {
                    wx.authorize({
                        scope: 'scope.bluetooth',
                        success: (res) => {
                            this.openBluetooth(); // 打开蓝牙适配器 
                        }
                    })
                }
                // (3) 已经授权
                if (res.authSetting['scope.bluetooth'] == true) {
                    this.openBluetooth(); // 打开蓝牙适配器 
                }
            },
            fail: () => {
                wx.showToast({ title: this.data.isZh ? "请检查网络连接" : "Network Error", icon: "error", mask: true });
                this.setData({ connecting: false, failedType: 0 });
            }
        })
    },
    openBluetooth() {
        this.setData({ connecting: true, failedType: 0, loadingMsg: this.data.isZh ? '正在搜索蓝牙' : 'Searching for a device' });
        let devices = [];
        // 打开蓝牙适配器
        wx.openBluetoothAdapter({
            success: (res) => {
                // console.log("打开蓝牙适配器成功：", res);
                // 监听扫描到新设备的事件
                wx.onBluetoothDeviceFound((result) => {
                    result.devices.forEach(device => {
                        // 使用iPad调试连接功能
                        // if (device.name.includes('iPad')) {
                        //     wx.setStorageSync('deviceId', device.deviceId);
                        // }
                        console.log(device);
                        if (this.data.routeName=="体温") {
                            if (device.name === "Bluetooth BP" || device.localName === "Bluetooth BP") {
                                // console.log(util.ab2hex(device.advertisServiceUUIDs));
                                !devices.some(item => device.deviceId === item.deviceId) && devices.push(device);
                            }
                        }else if(this.data.routeName=="血氧"){
                            console.log(device.name);
                            if (device.name === "MD300CI218" || device.localName === "MD300CI218") {
                                // console.log(util.ab2hex(device.advertisServiceUUIDs));
                                console.log(device);
                                !devices.some(item => device.deviceId === item.deviceId) && devices.push(device);
                            }
                        }
                       
                    })
                })
                // 开始搜寻附近的蓝牙外设
                wx.startBluetoothDevicesDiscovery({
                    allowDuplicatesKey: true,
                });
                // 3秒后停止搜寻
                this.setData({
                    timer: setTimeout(() => {
                        wx.stopBluetoothDevicesDiscovery();
                        console.log("设备列表", devices);
                        if (!devices.length) {
                            this.setData({ connecting: false, failedType: 3 });
                            this.showErr();
                        } else if (devices.length > 1) {
                            this.setData({ connecting: false, failedType: 2 });
                            this.showErr();
                        } else {
                            this.setData({ loadingMsg: this.data.isZh ? '正在连接' : 'Connecting', });
                            this.connectById(devices[0].deviceId);
                        }
                    }, 3000)
                });
            },
            fail: (res) => {
                console.error("打开蓝牙适配器失败：", res)
                // if (res.errCode !== 10001) return;
                this.setData({ connecting: false, failedType: 1 });
                this.showErr();
                wx.onBluetoothAdapterStateChange((res) => {
                    if (!res.available) return;
                    // 开始搜寻附近的蓝牙外设
                    wx.startBluetoothDevicesDiscovery({
                        allowDuplicatesKey: true,
                    })
                })
            }
        });
    },
    connectById(deviceId) {
        wx.createBLEConnection({
            deviceId, // 搜索到设备的 deviceId
            success: () => {
                console.log("已连接设备", deviceId)
                // wx.setStorageSync('deviceId', deviceId);
                // wx.setStorageSync('bindTime', Date.now());
                wx.setStorageSync('routeName', this.data.routeName);
                if (this.data.routeName=="体温") {
                    wx.setStorageSync('deviceId', deviceId);
                    wx.setStorageSync('bindTime', Date.now());
                    setTimeout(wx.navigateTo, 1000, { url: '../operation/operation' });
                    console.log('已连接设备: ' + deviceId)
                }else if(this.data.routeName=='血氧'){
                    console.log(1);
                    wx.setStorageSync('oximeterDeviceId', deviceId);
                    wx.setStorageSync('bindTime', Date.now());
                    setTimeout(wx.navigateTo, 1000, { url: '../oximeter/oximeter' });
                    console.log('已连接设备: ' + deviceId)
                }
                wx.showToast({ title: this.data.isZh ? '已连接' : 'Connected', icon: 'success', mask: true });
               
               
            },
            fail: (res) => {
                console.error("连接失败", res)
                // wx.showToast({ title: this.data.isZh ? "蓝牙连接失败" : "Bluetooth connection failed", icon: 'error', mask: true });
                this.setData({ connecting: false, failedType: 1 });
                this.showErr();
            }
        });
    },
    showErr() {
        switch (this.data.failedType) {
            case 1:
                this.setData({
                    errTitle: this.data.isZh ? "蓝牙连接失败" : "Bluetooth connection failed",
                    errSubtitle: this.data.isZh ? "请确认手机蓝牙处于开启状态\n并对微信授权蓝牙功能" : "Make sure that Bluetooth is on\nand and allow wechat to access"
                });
                break;
            case 2:
                this.setData({
                    errTitle: this.data.isZh ? "识别到过多设备" : "Find multiple devices",
                    errSubtitle: this.data.isZh ? "手机识别到多个处于开启带连接的设备\n建议您等待一段时间后再次尝试" : "Multiple infrared thermometers are found\nwaiting to be connected within the Bluetooth\nconnection range. It is recommended to wait\nfor a while and try again"
                });
                break;
            case 3:
                this.setData({
                    errTitle: this.data.isZh ? "未检测到设备" : "Device not found",
                    errSubtitle: this.data.isZh ? "请确认额温枪已开机\n看到蓝牙开始闪烁后再次连接" : "Make sure the infrared thermometer is\nturnedon and the bluetooth icon on the screen\nis flashing."
                });
                break;
        }
    }
})